package com.xyf.sys.controller;

import com.xyf.sys.config.MiniprogramConfig;
import com.xyf.sys.domain.GoodsCartItem;
import com.xyf.sys.service.IGoodsCartService;
import com.xyf.sys.util.R;
import com.xyf.sys.vo.GoodsCartPreOrderParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author R-H
 * @Date 2024-8
 * @Description
 */
@RestController
@RequestMapping("/goodsCart")
@Slf4j
@Api(tags = "购物车")
public class GoodsCartController {

    @Autowired
    private IGoodsCartService goodsCartService;
    @Autowired
    @Qualifier(value = "clientConfig")
    private MiniprogramConfig.MiniConfig clientConfig;

    @ApiOperation(value = "查询我的购物车", notes = "查询我的购物车")
//    @GetMapping("/query")
    public Object query(@RequestParam(required = false) String userId, HttpServletRequest request) {
        if (StringUtils.isBlank(userId)) {
            userId = request.getHeader("openid");
        }
        String appid = request.getHeader("APPID");
        boolean client = clientConfig.getAppid().equals(appid);
        return R.ok(goodsCartService.getUserCart(userId));
    }

    @ApiOperation(value = "添加编辑购物车", notes = "添加编辑购物车")
//    @PostMapping("/add")
    public Object add(@RequestBody GoodsCartItem item, HttpServletRequest request) {
        String appid = request.getHeader("APPID");
        boolean client = clientConfig.getAppid().equals(appid);
        item.setUserId(appid);
        return R.ok(goodsCartService.add(item));
    }

    @ApiOperation("删除购物车")
    @PostMapping("/remove")
    public Object remove(@RequestBody GoodsCartItem body, HttpServletRequest request) {
        goodsCartService.removeItem(body.getId(), body.getUserId());
        return R.ok(goodsCartService.getUserCart(body.getUserId()));
    }

    @ApiOperation(value = "清空购物车", notes = "清空购物车")
    @PostMapping("/clear")
    public Object clear(HttpServletRequest request) {
        String appid = request.getHeader("APPID");
        boolean client = clientConfig.getAppid().equals(appid);
        return R.ok(goodsCartService.clearCart(request.getHeader("openid")));
    }

    @ApiOperation("下单")
    @PostMapping("/preOrder")
    public Object preOrder(@RequestBody GoodsCartPreOrderParam orderParam, HttpServletRequest request) {
        orderParam.setAppid(request.getHeader("APPID"));
        orderParam.setUserId(request.getHeader("OPENID"));
        return R.ok(goodsCartService.newOrder(orderParam));
    }
}
